<template>
    <el-form-item
        label="渲染类型"
        :rules="{
            required: true,
            message: '类型不能为空',
            trigger: 'blur',
        }"
    >
        <el-select v-model="rasterRenderType" placeholder="Select" size="small" @change="rasterRenderTypeChangeHandler">
            <el-option
                v-for="rasterRenderTypeItem in rasterRenderTypes"
                :key="rasterRenderTypeItem.value"
                :label="rasterRenderTypeItem.label"
                :value="rasterRenderTypeItem.value"
            />
        </el-select>
    </el-form-item>
    <el-form-item v-if="rasterRenderType == 'singleBandPseudocolor'" label="波段">
        <el-select
            v-if="channelOptions.length > 0"
            v-model="localRuleOption.channelSelection"
            placeholder="Select"
            size="small"
        >
            <template v-for="(channelItem, channelIndex) in channelOptions" :key="'channelIndex' + channelIndex">
                <el-option
                    v-if="Object.hasOwnProperty.call(channelItem, 'grayChannel')"
                    :label="(channelItem as GrayChannel).grayChannel.sourceChannelName"
                    :value="channelItem"
                />
                <el-option
                    v-if="Object.hasOwnProperty.call(channelItem, 'redChannel')"
                    :label="(channelItem as RGBChannel).redChannel.sourceChannelName"
                    :value="channelItem"
                />
                <el-option
                    v-if="Object.hasOwnProperty.call(channelItem, 'blueChannel')"
                    :label="(channelItem as RGBChannel).blueChannel.sourceChannelName"
                    :value="channelItem"
                />
                <el-option
                    v-if="Object.hasOwnProperty.call(channelItem, 'greenChannel')"
                    :label="(channelItem as RGBChannel).greenChannel.sourceChannelName"
                    :value="channelItem"
                />
            </template>
        </el-select>
    </el-form-item>
    <el-form-item v-if="rasterRenderType == 'singleBandPseudocolor'" label="配色方式">
        <el-select
            v-model="colorRenderType"
            placeholder="请选择配色方式"
            size="small"
            @change="colorRenderTypeChangeHandler"
        >
            <el-option
                v-for="colorRenderTypeItem in colorRenderTypes"
                :key="colorRenderTypeItem.value"
                :label="colorRenderTypeItem.label"
                :value="colorRenderTypeItem.value"
            />
        </el-select>
    </el-form-item>
    <el-form-item v-if="rasterRenderType != 'common'" label="配色条">
        <el-select
            v-model="rasterColorStripInfo"
            placeholder="Select"
            size="small"
            @change="rasterColorStripsChangeHandler"
        >
            <template #label>
                <colorStrip
                    v-if="rasterColorStripInfo"
                    :gradient="rasterColorStripInfo?.gradient"
                    :color-option="rasterColorStripInfo?.colorOpt"
                />
            </template>
            <el-option
                v-for="(colorStripItem, colorStripIndex) in renderColorStripConfig"
                :key="'colorStripIndex' + colorStripIndex"
                :label="colorStripItem.label"
                :value="colorStripItem"
            >
                <colorStrip :gradient="colorStripItem.gradient" :color-option="colorStripItem.colorOpt" />
            </el-option>
        </el-select>
    </el-form-item>
    <el-form-item v-if="rasterRenderType != 'common'" label="映射表">
        <el-button type="primary" text @click="setColorMapping"> 点击查看 </el-button>
    </el-form-item>
    <colorMappingDialog
        v-if="colorMappingDialogVisible"
        v-model:visible="colorMappingDialogVisible"
        layerType="raster"
        :colorRenderType="colorRenderType"
        :colorMapEntrys="(localRuleOption.colorMap?.colorMapEntries as any)"
        :colorStrip="(rasterColorStripInfo as any)"
        @update-raster-color-map="updateRasterColorMap"
    ></colorMappingDialog>
</template>
<script setup lang="ts">
import { computed, reactive, ref, toRef, watch } from 'vue'
import type {
  Symbolizer as GeoSymbolizer,
  RasterSymbolizer as GeoRasterSymbolizer,
  ChannelSelection,
  GrayChannel,
  ColorMapType,
  ColorMap,
  RGBChannel,
  ColorMapEntry,
} from 'geostyler-style'
import colorStrip from '@/components/Color/colorStrip.vue'
import colorMappingDialog from '@/components/Color/color-mapping-dialog.vue'
import { type colorStripType } from '@/interface/color'
import { gradientColor, multipleGradientColor } from '@/utils/color'
import { RENDER_COLOR_STRIP } from '@/config/color'
import { ElMessage } from 'element-plus'
interface propsType {
    channelSelections?: ChannelSelection[]
    geoSymbolizer: GeoRasterSymbolizer
    bindInfo?: {
        //波段数量
        bandCount?: number
        //波段详情信息 JSON字符串
        bandMinMax?: {
            min: number
            max: number
            avg: number
            stddev: number
        }[]
    }
}
const props = withDefaults(defineProps<propsType>(), {
    channelSelections: () => {
        return []
    },
    geoSymbolizer: () => {
        return {
            kind: 'Raster', // 规则类型
            colorMap: undefined,
            channelSelection: undefined,
        }
    },
    bindInfo: () => {
        return {
            //波段数量
            bandCount: 1,
        }
    },
})
interface updateInnerStyleEmit {
    (e: 'updateInnerStyle', localRuleOption: GeoSymbolizer): void
}
const emit = defineEmits<updateInnerStyleEmit>()
/**
 * @description: 更新样式
 * @param {*} innerStyle
 * @return {*}
 */
const updateInnerStyle = (innerStyle: GeoRasterSymbolizer) => {
    emit('updateInnerStyle', innerStyle)
}

const colorMappingDialogVisible = ref(false)
// 配色方式
const colorRenderType = ref<ColorMapType>('ramp')
const colorRenderTypes = [
    {
        label: '渐变', //也叫线性
        value: 'ramp',
    },
    {
        label: '分段', // 也叫离散
        value: 'intervals',
    },
    {
        label: '唯一值', // 也叫准确
        value: 'values',
    },
]
// 配色条信息
const rasterColorStripInfo = ref<colorStripType>()
const rasterRenderType = ref('common')
const rasterRenderTypes = [
    {
        label: '通用',
        value: 'common',
    },
    {
        label: '单波段伪彩色',
        value: 'singleBandPseudocolor',
    },
    {
        label: '多波段彩色',
        value: 'multiBandColor',
    },
]

const channelOptions = toRef(props, 'channelSelections')
// 栅格规则
const localRuleOption = toRef(props, 'geoSymbolizer')

// const localRuleOption = ref<GeoRasterSymbolizer>({
//     kind: 'Raster', // 规则类型
//     colorMap: undefined,
//     channelSelection: undefined,
// })

// 颜色条下拉数据
const renderColorStripConfig = computed(() => {
    return RENDER_COLOR_STRIP.map((mapItem: any) => {
        return {
            ...mapItem,
            colorOpt: mapItem.colorOpt
                ? mapItem.colorOpt
                : gradientColor(mapItem.startColor, mapItem.endColor, mapItem.count, mapItem.step),
        } as colorStripType
    })
})
const rasterRenderTypeChangeHandler = () => {
    if (rasterRenderType.value == 'singleBandPseudocolor') {
        //vue3prop传值的第一级不允许编辑，所以用emit方式更新值
        updateInnerStyle({
            kind: 'Raster',
            colorMap: undefined,
            channelSelection: undefined,
        })
    } else if (rasterRenderType.value == 'common') {
        updateInnerStyle({
            kind: 'Raster',
            opacity: 1,
        })
        // localRuleOption.value = {
        //     kind: 'Raster',
        //     opacity: 1,
        // }
    } else {
        updateInnerStyle({
            kind: 'Raster',
            colorMap: undefined,
            channelSelection: undefined,
        })
    }
}
/**
 * @description: 配色方式改变事件
 * @return {*}
 */
const colorRenderTypeChangeHandler = () => {}

/**
 * @description:配色条下拉改变事件
 * @return {*}
 */
const rasterColorStripsChangeHandler = () => {
    console.log(rasterColorStripInfo)
    if (rasterColorStripInfo.value) {
        const colorPreSetArrays = rasterColorStripInfo.value!.colorOpt
            ? rasterColorStripInfo.value!.colorOpt
            : gradientColor(
                  rasterColorStripInfo.value.startColor,
                  rasterColorStripInfo.value.endColor,
                  rasterColorStripInfo.value.count,
                  rasterColorStripInfo.value.step,
              )
        // 默认5个区间
        const defaultColorNumber = 5
        const colorArrays = multipleGradientColor(colorPreSetArrays, defaultColorNumber)
        let startNumber = 0
        let intervelNumber = 1
        if (props.bindInfo && props.bindInfo.bandMinMax && props.bindInfo.bandMinMax.length > 0) {
            startNumber = props.bindInfo.bandMinMax[0].min
            intervelNumber =
                (props.bindInfo.bandMinMax[0].max - props.bindInfo.bandMinMax[0].min) / (defaultColorNumber - 1)
        }
        // 使用逻辑运算符来创建 colorMap 属性，如果它不存在的话
        localRuleOption.value.colorMap = {
            type: colorRenderType.value,
            colorMapEntries: colorArrays.map((mapItem, mapIndex) => {
                return {
                    color: mapItem,
                    quantity: startNumber + mapIndex * intervelNumber,
                    label: String(startNumber + mapIndex * intervelNumber),
                    opacity: 1,
                } as ColorMapEntry
            }),
        }
    }
}
/**
 * @description: 设置颜色映射表
 * @return {*}
 */
const setColorMapping = () => {
    if (rasterColorStripInfo.value) {
        colorMappingDialogVisible.value = true
    } else {
        ElMessage({
            type: 'warning',
            message: '请先选择配色条！',
        })
    }
}
/**
 * @description: 更新颜色映射表
 * @param {ColorMap} colorMap
 * @return {*}
 */
const updateRasterColorMap = (colorMap: ColorMap) => {
    localRuleOption.value.colorMap = colorMap
}

watch(
    () => props.geoSymbolizer,
    val => {
        if (val.colorMap?.type) {
            colorRenderType.value = val.colorMap?.type as ColorMapType
        }
        if (Object.keys(val).length == 2 && Object.keys(val)[1] == 'opacity') {
            rasterRenderType.value = 'common'
        }
        // 有colorMap的话则进行回显
        if (val.colorMap?.colorMapEntries && val.colorMap.colorMapEntries.length > 0) {
            rasterRenderType.value = 'singleBandPseudocolor'
            rasterColorStripInfo.value = {
                startColor: val.colorMap.colorMapEntries[0]!.color as string,
                endColor: val.colorMap.colorMapEntries[val.colorMap.colorMapEntries.length - 1]!.color as string,
                name: 'edit',
                value: 'edit',
                label: 'edit',
                count: 5,
                step: 5,
                colorOpt: val.colorMap.colorMapEntries.map(mapItem => {
                    return mapItem.color as string
                }),
                colorStrip: true,
                gradient: true,
            }
        } else {
            // 没有的话默认是单波段灰
            //rasterRenderType.value = 'singleBandGrey'
            // if (localRuleOption.value.name == 'Opaque Raster') {
            // }
        }
    },
)
// watch(
//     () => localRuleOption.value,
//     () => {
//         if (watchLocalRuleOptionStatus.value) {
//             emit('updateInnerStyle', localRuleOption.value as GeoRasterSymbolizer)
//         }
//     },
//     {
//         deep: true,
//         immediate: true,
//     },
// )
watch(
    () => channelOptions.value,
    () => {
        // if (
        //     Object.hasOwnProperty.call(channelOptions.value[0], 'redChannel') &&
        //     Object.hasOwnProperty.call(channelOptions.value[0], 'greenChannel') &&
        //     Object.hasOwnProperty.call(channelOptions.value[0], 'blueChannel')
        // ) {
        //     rasterRenderType.value == 'multiBandColor'
        // } else {
        //     rasterRenderType.value = 'singleBandGrey'
        // }
    },
    {
        immediate: true,
        deep: true,
    },
)
</script>
<style lang="scss" scoped></style>
